<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" @submit.native.prevent>
      <el-form-item label="关键字" prop="search">
        <el-input v-model="queryParams.search" placeholder="UID、昵称、电话号码" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="VIP等级" prop="vipLevel">
        <el-select v-model="queryParams.vipLevel" placeholder="VIP等级" clearable style="width: 240px">
          <el-option v-for="dict in vipLevelList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="活跃度" prop="isLowActivity">
        <el-select v-model="queryParams.isLowActivity" placeholder="活跃度" clearable style="width: 240px">
          <el-option v-for="dict in isLowActivityList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="注册时间">
        <el-date-picker v-model="dateRange" style="width: 340px" type="datetimerange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <el-table :height="tableHeight" v-loading="loading" :data="list" @sort-change="changeTableSort" @row-dblclick="handleUpdate" stripe border>
      <el-table-column label="序号" type="index" align="center" width="60" />
      <el-table-column label="姓名" prop="name" align="center" />
      <el-table-column label="UID" prop="id" align="center" :sortable="'custom'" />
      <el-table-column label="昵称" prop="nickname" align="center" />
      <el-table-column label="电话号码" prop="phone" align="center" width="120" />
      <el-table-column label="现金账户金额" prop="appUserAccCash.cashAmount" align="center" width="140" :sortable="'custom'" />
      <el-table-column label="冻结保证金" prop="appUserAccCash.freezeAmount" align="center" width="120" :sortable="'custom'" />
      <el-table-column label="佣金账户余额" prop="appUserAccBrokerage.brokerageAmount" align="center" width="140" :sortable="'custom'" />
      <el-table-column label="消费券余额" prop="appUserAccConsume.consumeAmount" align="center" width="120" :sortable="'custom'" />
      <el-table-column label="金积分账户余额" prop="appUserAccIntegral.goldAmount" align="center" width="140" :sortable="'custom'" />
      <el-table-column label="银积分账户余额" prop="appUserAccIntegral.silverAmount" align="center" width="140" :sortable="'custom'" />
      <el-table-column label="账号状态" prop="lockState" align="center" width="100">
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.lockState ==1">停用</el-tag>
          <el-tag v-else>正常</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="填写邀请码" prop="inviteCode" align="center" width="120" :sortable="'custom'" />
      <el-table-column label="信用指数" prop="appUserArtist.artExponent" :sortable="'custom'" v-if="checkPermi(['memeber:look:artExponent'])" align="center" width="100" />
      <el-table-column label="VIP等级" prop="vipLevel" align="center" width="120" :sortable="'custom'">
        <template slot-scope="scope">
          <span>{{selectDictLabel(vipLevel,scope.row.vipLevel)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" prop="createTime" width="160" align="center" :sortable="'custom'">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上次活跃时间" prop="activeSign" align="center" width="180" :sortable="'custom'" />
      <el-table-column label="VIP有效期" prop="vipEndTime" align="center" width="160" :sortable="'custom'" />
      <el-table-column label="设备号" prop="deviceId" align="center" min-width="180" />
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click.stop="handleUpdate(scope.row)" v-hasPermi="['member:manager.edit']">编辑</el-button>
          <el-button v-if="scope.row.lockState == 1" size="mini" type="text" @click.stop="userStateChange(scope.row)" v-hasPermi="['member:manager:isDisable']">启用</el-button>
          <el-button v-else size="mini" type="text" @click.stop="userStateChange(scope.row)" v-hasPermi="['member:manager:isDisable']">拉黑</el-button>
          <el-button size="mini" type="text" @click.stop="showEditParent(scope.row)" v-hasPermi="['member:manage:editParent']">修改推荐人</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <div v-if="open">
      <z-dialog :title="title" :width="'80%'" :visible.sync="open" @confirm="submitForm('formView')">
        <form-view :form="form" ref="formView"></form-view>
      </z-dialog>
    </div>

    <z-dialog :title="title" :visible.sync="showTJ" @confirm="editParentClick('formView')">
      <el-form ref="formTJ" :model="formTJ" label-width="150px">
        <el-form-item label="推荐人" prop="inviteCode">
          <el-input v-model="formTJ.inviteCode" />
        </el-form-item>
      </el-form>
    </z-dialog>
  </div>
</template>

<script>
import { getVipList, updateUser, userStopOrEnable, editParent } from "@/api/vip/vip.js";
import formView from './formView'
import { deepClone } from '@/utils/index'
import { checkPermi } from "@/utils/permission"; // 权限判断函数
import hasPer from "@/directive/permission/hasPer.js";

export default {
  name: "MemberManagement", //会员管理
  components: { formView },
  data() {
    return {
      // 列表数据
      list: [],

      dialogVisible: false,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,

      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      showTJ: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: this.global.pageSize,
      },
      pageNum: 1,
      // 表单参数
      form: {},
      formTJ: {},
      dateRange: [],
      rules: {

      },
      //VIP等级（0普通用户，1有效会员，2嘉宾，3黄金）
      vipLevel: [{ label: '普通用户', value: 0 }, { label: '有效会员', value: 1 }, { label: '银牌会员', value: 2 }, { label: '金牌会员', value: 3 }],
      isLowActivity: [{ label: '低活', value: 1 }, { label: '高活', value: 2 }],
      lockState: [{ label: '正常', value: 0 }, { label: '停用', value: 1 }], //会员状态
    };
  },
  watch: {
    "queryParams": {
      deep: true,
      handler: function (newV, oldV) {

        if (this.pageNum == newV.pageNum) {
          this.handleQuery();
        } else {
          this.pageNum = newV.pageNum;
        }
      },
    },
    dateRange(newV, oldV) {
      if (newV) {
        if (newV.length >= 2) {
          this.queryParams.createTimeStart = String(newV[0]);
          this.queryParams.createTimeEnd = String(newV[1]);
        }
      } else {
        this.queryParams.createTimeStart = undefined;
        this.queryParams.createTimeEnd = undefined;
      }
      this.getList();

    }
  },
  computed: {
    tableHeight() {
      return 'calc(100vh - 280px)'
    },
    vipLevelList() {
      let typeDictArray = JSON.parse(JSON.stringify(this.vipLevel));
      typeDictArray.unshift({ label: "全部", value: undefined });
      return typeDictArray;
    },
    isLowActivityList() {
      let typeDictArray = JSON.parse(JSON.stringify(this.isLowActivity));
      typeDictArray.unshift({ label: "全部", value: undefined });
      return typeDictArray;
    },
  },
  created() {
    this.getList();
  },
  methods: {
    checkPermi,
    getList() {
      this.loading = true;
      getVipList(this.queryParams).then((response) => {
        if (response.code == 200) {
          this.list = response.data;
          this.total = response.total;
        }
        this.loading = false;
      });
    },
    changeTableSort(column) {
      let paraStr = column.prop;
      let arr = [];
      if (paraStr.indexOf(".") != -1) {
        arr = paraStr.split('.')
        paraStr = arr.length > 1 ? arr[1] : '';
      }
      this.queryParams.orderBy = paraStr;
      this.queryParams.isAsc = (column.order == 'descending' ? 0 : 1); //ascending == 升序 descending == 降序  0 倒,1正
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.createTimeStart = undefined;
      this.queryParams.createTimeEnd = undefined;
      this.dateRange = undefined;
      this.handleQuery();
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      if (!hasPer.isPerShow(['member:manager.edit'])) {
        return;
      }
      this.reset();
      this.title = "会员信息";
      this.open = true;
      this.form = deepClone(row);
      console.log(this.form)
    },


    showEditParent(row) {
      this.reset();
      this.showTJ = true;
      this.formTJ = JSON.parse(JSON.stringify(row));
      this.title = '更换推荐人';
    },

    editParentClick() {
      let params = {
        "userId": this.formTJ.id,
        "parentId": this.formTJ.inviteCode
      };
      editParent(params).then((response) => {
        this.$modal.msgSuccess("操作成功");
        this.showTJ = false;
        this.getList();
      });
    },

    /** 提交按钮 */
    submitForm(ref) {
      let params = this.$refs[ref].$refs.first.params
      let formUser = this.$refs[ref].$refs.first.$refs.user
      if (params.adminUser != this.form.adminUser || params.nickName != this.form.nickname || params.name != this.form.name || params.idCard != this.form.idCard) {
        formUser.validate(valid => {
          if(valid){
             updateUser(params).then((response) => {
                if (response.code == 200) {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
          }
        })
      } else {
        this.open = false;
      }
    },

    //拉黑操作
    userStateChange(row) {
      let params = {
        id: row.id,
        lockState: row.lockState == '1' ? 0 : 1
      }
      let str = (row.lockState == '1' ? '启用' : '拉黑')
      this.$modal
        .confirm('是否把账号为"' + row.id + '"的用户"' + str + '"?')
        .then(() => {
          userStopOrEnable(params).then((response) => {
            this.$modal.msgSuccess("操作成功");
            this.getList();
          });
        }
        ).catch(() => { });
    }

  },
};
</script>
<style scoped>
</style>
